package com.rongke.web.api;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.commons.PageDto;
import com.rongke.mapper.IndexMapper;
import com.rongke.model.Channel;
import com.rongke.model.LoanOrder;
import com.rongke.model.User;
import com.rongke.service.ChannelService;
import com.rongke.service.LoanOrderService;
import com.rongke.service.UserService;
import com.rongke.utils.Md5;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ChannelController
 * @Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/channel")
@Transactional
@CrossOrigin
public class ChannelController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private ChannelService channelService;
    @Autowired
    private UserService userService;
    @Autowired
    private LoanOrderService loanOrderService;
    @Autowired
    private IndexMapper indexMapper;

    /**
     * @添加
     * @param channel
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public JsonResp addChannel(@RequestBody Channel channel){
        log.debug("添加");
        if (channel.getId() == null) {
            EntityWrapper<Channel> wrapper = new EntityWrapper<>();
            wrapper.eq("name",channel.getName());
            EntityWrapper<Channel> wrapper1 = new EntityWrapper<>();
            wrapper1.eq("login_name",channel.getLoginName());
            Channel channel1 = channelService.selectOne(wrapper);
            if (channel1 != null) {
                return JsonResp.toFail("渠道商名称已存在");
            }
            Channel channel2 = channelService.selectOne(wrapper1);
            if (channel2 != null) {
                return JsonResp.toFail("渠道商登录账号已存在");
            }
            channelService.insertOrUpdate(channel);
            String linkUrl = "http://www.51jishiyu.cn:8080/share/index.html?channelName="+channel.getName();
            channel.setLinkUrl(linkUrl);
            channel.setPassword(Md5.md5Encode(channel.getPassword()));
        }else {
            Channel channel1 = channelService.selectById(channel.getId());
            channel.setPassword(channel1.getPassword());
        }
        channel.setStatus(1);
        channelService.insertOrUpdate(channel);
        return JsonResp.ok(channel);
    }

    /**
     * @修改
     * @param channel
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public JsonResp updateChannel(@RequestBody Channel channel){
        log.debug("修改");
        channelService.updateById(channel);
        return JsonResp.ok(channel);
    }
    /**
     * @根据id查找
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOne", method = RequestMethod.GET)
    public JsonResp selectChannel(Long id){
        log.debug("查找");
        Channel channel = channelService.selectById(id);
        return JsonResp.ok(channel);
    }


    /**
     * @param
     * @return 返回值JsonResp
     * @根据id查找管理员
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public JsonResp login(String userName, String password){
        log.debug("登录");
        return JsonResp.ok(userService.channelLogin(userName,password));
    }


    /**
     * @param
     * @return 返回值JsonResp
     * @获取当前登录渠道商
     */
    @RequestMapping(value = "/getThisLogin", method = RequestMethod.GET)
    public JsonResp getThisLogin(){
        log.debug("获取当前登录渠道商");
        Channel channel = userService.getCurentChannel();
        return JsonResp.ok(channel);
    }


    /**
     * @查找列表
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectList", method = RequestMethod.GET)
    @RequiresAuthentication
    public JsonResp selectList(Integer pageNo, Integer pageSize, String loginName){
        log.debug("查找列表");
        Page page = new Page(pageNo,pageSize);
        EntityWrapper<Channel> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("status",1);
        if (!loginName.equals("")) {
            entityWrapper.like("login_name",loginName);
        }
        page = channelService.selectPage(page,entityWrapper);

        return JsonResp.ok(new PageDto(pageNo,pageSize,page.getRecords(),page.getTotal()));
    }


    /**
     * @删除
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/deleteOne", method = RequestMethod.GET)
    public JsonResp deleteOne(Long id){
        log.debug("删除");
        Channel channel = channelService.selectById(id);
        channel.setStatus(2);
        channelService.updateById(channel);
        return JsonResp.ok();
    }


    /**
     * @渠道商查询自己的注册会员
     * @param channelId(不为空说明后台查询指定   否则渠道商查询自己)
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/findMyMember", method = RequestMethod.GET)
    public JsonResp findMyMember(Integer pageNo, Integer pageSize, String phone, String userName, Long channelId){
        log.debug("渠道商查询自己的注册会员");
        Page page = new Page(pageNo,pageSize);
        Channel channel = new Channel();
        if (channelId == null) {
            channel = userService.getCurentChannel();
        }else {
            channel = channelService.selectById(channelId);
        }
        EntityWrapper<User> wrapper = new EntityWrapper();
        wrapper.eq("channel_id",channel.getId());
        if (!phone.equals("")) {
            wrapper.like("phone",phone);
        }
        if (!userName.equals("")) {
            wrapper.like("user_name",userName);
        }
        page = userService.selectPage(page,wrapper);
        return JsonResp.ok(new PageDto(pageNo,pageSize,page.getRecords(),page.getTotal()));
    }


    /**
     * @param
     * @return 返回值JsonResp
     * @报表统计
     */
    @RequestMapping(value = "/statementSelect", method = RequestMethod.GET)
    public JsonResp statementSelect(){
        log.debug("报表统计");
        Channel channel = userService.getCurentChannel();
        Map<String,Object> map = new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        map.put("time",format.format(date));
        map.put("channelName",channel.getLoginName());
        Integer userAddCountChannel = indexMapper.userAddCountChannel(map);
        String orderOutMoneyChannel  = indexMapper.orderOutMoneyChannel(map);
        String applyOrderMoneyChannel = indexMapper.applyOrderMoneyChannel(map);
        String orderChannelProfitChannel = indexMapper.orderChannelProfitChannel(map);
        Map<String,Object> map1 = new HashMap<>();
        if (userAddCountChannel == null) {
            userAddCountChannel = 0;
        }
        if (orderOutMoneyChannel == null) {
            orderOutMoneyChannel = "0";
        }
        if (applyOrderMoneyChannel == null) {
            applyOrderMoneyChannel = "0";
        }
        if (orderChannelProfitChannel == null) {
            orderChannelProfitChannel = "0";
        }
        map1.put("userAddCountChannel",userAddCountChannel);
        map1.put("orderOutMoneyChannel",orderOutMoneyChannel);
        map1.put("applyOrderMoneyChannel",applyOrderMoneyChannel);
        map1.put("orderChannelProfitChannel",orderChannelProfitChannel);
        map1.put("channel",channel);
        return JsonResp.ok(map1);
    }

    /**
     * @param
     * @return 返回值JsonResp
     * @报表统计
     */
    @RequestMapping(value = "/findMoneyStatistics", method = RequestMethod.GET)
    public JsonResp findMoneyStatistics(String year) {
        log.debug("报表统计");
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        map1.put("giveTime", year);
        map2.put("realPayTime", year);
        List<LoanOrder> list = loanOrderService.orderListChannel(map1);
        List<LoanOrder> list1 = loanOrderService.orderListChannel(map2);
        List<BigDecimal> outMoneys = new ArrayList<>();
        List<BigDecimal> backMoneys = new ArrayList<>();
        List<BigDecimal> profits = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            String year1 = year + "-0" + (i + 1);
            BigDecimal outMoney = new BigDecimal("0");
            BigDecimal backMoney = new BigDecimal("0");
            BigDecimal profit = new BigDecimal("0");
            if (i >= 9) {
                year1 = year + "" + i + 1 + "";
            }
            for (LoanOrder loanOrder : list) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String date = format.format(loanOrder.getGiveTime());
                if (date.contains(year1)) {
                    outMoney = outMoney.add(loanOrder.getRealMoney());
                }
            }
            for (LoanOrder loanOrder : list1) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (loanOrder.getGiveTime() == null) {
                    int a = 1;
                }
                String date = format.format(loanOrder.getRealPayTime());
                if (date.contains(year1)) {
                    backMoney = backMoney.add(loanOrder.getNeedPayMoney());
                    profit = profit.add(loanOrder.getChannelProfit());
                }
            }
            outMoneys.add(outMoney);
            backMoneys.add(backMoney);
            profits.add(profit);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("outMoneys", outMoneys);
        map.put("backMoneys", backMoneys);
        map.put("profits", profits);
        return JsonResp.ok(map);
    }
}
